package ltd.newbee.mall.api.mall;

import ltd.newbee.mall.entity.GoodsSpecAttr;
import ltd.newbee.mall.entity.GoodsSpecValue;
import ltd.newbee.mall.service.GoodsSpecService;
import ltd.newbee.mall.util.Result;
import ltd.newbee.mall.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品规格控制器
 */
@RestController
@RequestMapping("/api/v1")
public class GoodsSpecController {

    @Autowired
    private GoodsSpecService goodsSpecService;

    /**
     * 获取商品的完整规格信息（包含属性及其值）
     */
    /**
     * 获取商品的完整规格信息（包含属性及其值）
     */
    @GetMapping("/full/{goodsId}")
    public Result getFullSpecByGoodsId(@PathVariable Long goodsId) {
        try {
            Map<GoodsSpecAttr, List<GoodsSpecValue>> fullSpec = goodsSpecService.getFullSpecByGoodsId(goodsId);

            // 直接返回列表格式
            List<Object> result = new ArrayList<>();
            for (Map.Entry<GoodsSpecAttr, List<GoodsSpecValue>> entry : fullSpec.entrySet()) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", entry.getKey().getId());
                item.put("goodsId", entry.getKey().getGoodsId());
                item.put("attrName", entry.getKey().getAttrName());
                item.put("attrKey", entry.getKey().getAttrKey());
                item.put("sortOrder", entry.getKey().getSortOrder());
                item.put("values", entry.getValue());
                result.add(item);
            }

            return ResultGenerator.genSuccessResult(result);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("获取商品规格失败: " + e.getMessage());
        }
    }

    /**
     * 根据商品ID获取规格属性列表
     */
    @GetMapping("/attrs/{goodsId}")
    public Result getAttrsByGoodsId(@PathVariable Long goodsId) {
        try {
            List<GoodsSpecAttr> attrs = goodsSpecService.getAttrsByGoodsId(goodsId);
            return ResultGenerator.genSuccessResult(attrs);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("获取规格属性失败: " + e.getMessage());
        }
    }

    /**
     * 根据属性ID获取属性值列表
     */
    @GetMapping("/values/{attrId}")
    public Result getValuesByAttrId(@PathVariable Long attrId) {
        try {
            List<GoodsSpecValue> values = goodsSpecService.getValuesByAttrId(attrId);
            return ResultGenerator.genSuccessResult(values);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("获取属性值失败: " + e.getMessage());
        }
    }

    /**
     * 根据商品ID获取所有属性值
     */
    @GetMapping("/values/goods/{goodsId}")
    public Result getValuesByGoodsId(@PathVariable Long goodsId) {
        try {
            List<GoodsSpecValue> values = goodsSpecService.getValuesByGoodsId(goodsId);
            return ResultGenerator.genSuccessResult(values);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("获取属性值失败: " + e.getMessage());
        }
    }

    /**
     * 添加规格属性
     */
    @PostMapping("/attr")
    public Result addAttr(@RequestBody GoodsSpecAttr attr) {
        try {
            boolean success = goodsSpecService.saveAttr(attr);
            if (success) {
                return ResultGenerator.genSuccessResult("添加成功");
            } else {
                return ResultGenerator.genFailResult("添加失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("添加规格属性失败: " + e.getMessage());
        }
    }

    /**
     * 更新规格属性
     */
    @PutMapping("/attr")
    public Result updateAttr(@RequestBody GoodsSpecAttr attr) {
        try {
            boolean success = goodsSpecService.saveAttr(attr);
            if (success) {
                return ResultGenerator.genSuccessResult("更新成功");
            } else {
                return ResultGenerator.genFailResult("更新失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("更新规格属性失败: " + e.getMessage());
        }
    }

    /**
     * 删除规格属性
     */
    @DeleteMapping("/attr/{id}")
    public Result deleteAttr(@PathVariable Integer id) {
        try {
            boolean success = goodsSpecService.deleteAttr(id);
            if (success) {
                return ResultGenerator.genSuccessResult("删除成功");
            } else {
                return ResultGenerator.genFailResult("删除失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("删除规格属性失败: " + e.getMessage());
        }
    }

    /**
     * 添加属性值
     */
    @PostMapping("/value")
    public Result addValue(@RequestBody GoodsSpecValue value) {
        try {
            boolean success = goodsSpecService.saveValue(value);
            if (success) {
                return ResultGenerator.genSuccessResult("添加成功");
            } else {
                return ResultGenerator.genFailResult("添加失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("添加属性值失败: " + e.getMessage());
        }
    }

    /**
     * 更新属性值
     */
    @PutMapping("/value")
    public Result updateValue(@RequestBody GoodsSpecValue value) {
        try {
            boolean success = goodsSpecService.saveValue(value);
            if (success) {
                return ResultGenerator.genSuccessResult("更新成功");
            } else {
                return ResultGenerator.genFailResult("更新失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("更新属性值失败: " + e.getMessage());
        }
    }

    /**
     * 删除属性值
     */
    @DeleteMapping("/value/{id}")
    public Result deleteValue(@PathVariable Integer id) {
        try {
            boolean success = goodsSpecService.deleteValue(id);
            if (success) {
                return ResultGenerator.genSuccessResult("删除成功");
            } else {
                return ResultGenerator.genFailResult("删除失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("删除属性值失败: " + e.getMessage());
        }
    }

    /**
     * 批量保存规格属性
     */
    @PostMapping("/attrs/batch")
    public Result batchSaveAttrs(@RequestBody List<GoodsSpecAttr> attrs) {
        try {
            boolean success = goodsSpecService.batchSaveAttrs(attrs);
            if (success) {
                return ResultGenerator.genSuccessResult("批量保存成功");
            } else {
                return ResultGenerator.genFailResult("批量保存失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("批量保存规格属性失败: " + e.getMessage());
        }
    }

    /**
     * 批量保存属性值
     */
    @PostMapping("/values/batch")
    public Result batchSaveValues(@RequestBody List<GoodsSpecValue> values) {
        try {
            boolean success = goodsSpecService.batchSaveValues(values);
            if (success) {
                return ResultGenerator.genSuccessResult("批量保存成功");
            } else {
                return ResultGenerator.genFailResult("批量保存失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("批量保存属性值失败: " + e.getMessage());
        }
    }

    /**
     * 删除商品的所有规格信息
     */
    @DeleteMapping("/goods/{goodsId}")
    public Result deleteAllByGoodsId(@PathVariable Long goodsId) {
        try {
            boolean success = goodsSpecService.deleteAllByGoodsId(goodsId);
            if (success) {
                return ResultGenerator.genSuccessResult("删除成功");
            } else {
                return ResultGenerator.genFailResult("删除失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("删除商品规格失败: " + e.getMessage());
        }
    }

    /**
     * 复制规格信息到其他商品
     */
    @PostMapping("/copy")
    public Result copySpecToGoods(@RequestParam Long sourceGoodsId,
                                  @RequestParam Long targetGoodsId) {
        try {
            boolean success = goodsSpecService.copySpecToGoods(sourceGoodsId, targetGoodsId);
            if (success) {
                return ResultGenerator.genSuccessResult("复制成功");
            } else {
                return ResultGenerator.genFailResult("复制失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("复制规格信息失败: " + e.getMessage());
        }
    }
}
